package com.xiaohong.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局拦截器
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    //令牌头名字
    private static final String AUTHORIZE_TOKEN = "Authorization";

    /**
     * 全局拦截
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        HttpMethod method = request.getMethod();
        // 判断是否时预检请求
//        if ( method == HttpMethod.OPTIONS){
//            // 直接返回空消息
//            return response.setComplete();
//        }

        //判断是否在拦截路径的白名单里
        String uri = request.getPath().toString();
        if (URLFilter.hasAuthorize(uri)){
            request.mutate().header("ip", exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
//            request.mutate().header("Access-Control-Allow-Origin", "*");
            //true表示不拦截
            return chain.filter(exchange);
        }

        //获取令牌信息
        //从头部获取
        String token = request.getHeaders().getFirst("Authorization");
        //flag 用来辨别请求头中是否有需要的token 令牌如果不在，就封装到请求头中，再传到其他微服务
//        Boolean flag = false;
        if (StringUtils.isEmpty(token)){
            token = request.getQueryParams().getFirst("Authorization");
        }
        //从Cookie中获取
        if (StringUtils.isEmpty(token)){
            HttpCookie httpCookie = request.getCookies().getFirst("Authorization");
            if (httpCookie != null){
                token = httpCookie.getValue();
            }
        }

        //如果是搜索，则从参数中获取令牌
//        if (uri.equals("/api/search/list")){
//            token = request.getURI().toString().split("token=")[1];
//        }

        //如果没有令牌信息则直接拒绝，返回空
        if (StringUtils.isEmpty(token)){
            // 设置错误码 401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回空信息
            return response.setComplete();
        }

        //如果获取到了，判断令牌信息是否正确
        /*try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            //不正确拒绝请求
            // 设置错误码 401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回空信息
            response.setComplete();
        }*/

        //判断令牌是否为空
        if (StringUtils.isEmpty(token)){
            //如果为空则直接拒绝
            // 设置错误码 401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回空信息
            response.setComplete();
        }else {
            //判断令牌是否有bearer 前缀
            if (!token.startsWith("bearer ")&&!token.startsWith("Bearer")){
                token="bearer "+token;
            }
        }

        request.mutate().header(AUTHORIZE_TOKEN,token);

        //正确放行
        return chain.filter(exchange);
    }

    /**
     * 排序 越小越先执行
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
